package search

import (
	"fmt"
	protos "goim-pro/api/protos/salty"
	"goim-pro/internal/app/models"
	. "goim-pro/internal/app/models/errors"
	"goim-pro/internal/app/repos/contact"
	"goim-pro/internal/app/repos/group"
	"goim-pro/internal/app/repos/user"
	mysqlsrv "goim-pro/internal/db/mysql"
	redsrv "goim-pro/internal/db/redis"
	"goim-pro/pkg/logs"
)

var (
	logger = logs.GetLogger("INFO")

	myRedis redsrv.IMyRedis

	userRepo    user.IUserRepo
	contactRepo contact.IContactRepo
	groupRepo   group.IGroupRepo
)

type ISearchService interface {
	Search(userId string, searchType protos.SearchType, searchContent string) (searchUsers []models.User, searchContacts []models.Contact, searchGroups []models.Group, tErr *TError)
}

type SearchService struct {
}

func New() ISearchService {
	myRedis = redsrv.GetRedis()

	userRepo = user.NewUserRepo(mysqlsrv.GetMysql())
	contactRepo = contact.NewContactRepo(mysqlsrv.GetMysql())
	groupRepo = group.NewGroupRepo(mysqlsrv.GetMysql())

	return &SearchService{}
}

func (s *SearchService) Search(userId string, searchType protos.SearchType, searchContent string) (searchUsers []models.User, searchContacts []models.Contact, searchGroups []models.Group, tErr *TError) {
	var err error
	switch searchType {
	case protos.SearchType_USER:
		searchUserCond := fmt.Sprintf("telephone = %s or email = %s", searchContent, searchContent)
		searchUsers, err = userRepo.FindAll(searchUserCond)
		if err != nil {
			return nil, nil, nil, NewTError(protos.StatusCode_STATUS_INTERNAL_SERVER_ERROR, err)
		}
	case protos.SearchType_CONTACT:
		//searchContactCond := fmt.Sprintf("(remarkName LIKE %s) or (telephone LIKE %s)", searchContent, searchContent)
		searchContacts, err = contactRepo.FuzzySearch(userId, searchContent)
		if err != nil {
			return nil, nil, nil, NewTError(protos.StatusCode_STATUS_INTERNAL_SERVER_ERROR, err)
		}
	case protos.SearchType_GROUP:
		// TODO:
	case protos.SearchType_ALL:
		searchUserCond := fmt.Sprintf("telephone = %s or email = %s", searchContent, searchContent)
		searchUsers, err = userRepo.FindAll(searchUserCond)
		if err != nil {
			return nil, nil, nil, NewTError(protos.StatusCode_STATUS_INTERNAL_SERVER_ERROR, err)
		}
		searchContacts, err = contactRepo.FuzzySearch(userId, searchContent)
		if err != nil {
			return nil, nil, nil, NewTError(protos.StatusCode_STATUS_INTERNAL_SERVER_ERROR, err)
		}
	}

	return searchUsers, searchContacts, nil, nil
}
